package cn.zhaozhiqi.productor;

import cn.zhaozhiqi.constants.Constants;
import cn.zhaozhiqi.pojo.domain.PayOrder;
import cn.zhaozhiqi.pojo.domain.WxpayFlow;
import cn.zhaozhiqi.service.IPayOrderService;
import cn.zhaozhiqi.service.IWxpayFlowService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.HashMap;

/**
 * 生产者
 */
@Slf4j
@RocketMQTransactionListener(txProducerGroup = Constants.Mq.PAY_SUCCESS_GROUP)
public class PaySuccessProductor implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IWxpayFlowService wxpayFlowService;

    /**
     * 执行本地事务
     * @param message  消息体本身
     * @param arg  额外传递的参数,其中有流水和统一支付单的保存方案
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            HashMap<String, Object> mapObj = (HashMap<String, Object>) arg;
            PayOrder payOrder = (PayOrder) mapObj.get("payOrder");
            WxpayFlow flow = (WxpayFlow) mapObj.get("flow");
            payOrderService.updateById(payOrder);
            wxpayFlowService.save(flow);
            return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//执行本地事务失败
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        return null;
    }
}
